package cgs

import (
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/base"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"net/http"
	"strings"
)

func init() {
	server.Handle(http.MethodGet, "/api/Cgs/Export", ExportCgs, server.None)
	server.Post("/api/Cgs/Proj/Save", Save, "添加或保存工程", server.Login)
	server.Post("/api/Cgs/Proj/ChangeName", ChangeName, "修改工程名称", server.Login)
	server.Post("/api/Cgs/Proj/ChangeData", ChangeData, "更新工程数据", server.Login)
	server.Post("/api/Cgs/Proj/Delete", Delete, "删除工程", server.Login)
	server.Get("/api/Cgs/Proj/List", List, "获取工程列表", server.None)
	server.Get("/api/Cgs/Proj/Get", Get, "获取工程", server.None)
	server.Get("/api/Cgs/Proj/js/list", ListJs, "获取工程脚本列表", server.None)
}

func ExportCgs(w http.ResponseWriter, r *http.Request) {
	id := strings.TrimSpace(r.FormValue("ProjId"))
	projectId, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  "ID is not allowed.",
		})
		return
	}

	CgsService := NewCgsService()
	zipData, _, err := CgsService.Export(projectId)

	if err != nil {
		_, _ = helper.WriteJSON(w, server.CgsResult{
			Code: 300,
			Msg:  err.Error(),
		})
		return
	}

	buf, err := base.ZipFile(zipData)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.CgsResult{
			Code: 300,
			Msg:  err.Error(),
		})
		return
	}
	//head.Set("ContentType", "application/octet-stream")
	//head.Set("CharacterEncoding", "UTF-8")
	n, _ := buf.WriteTo(w)

	fmt.Println("字节数：", n)
}

func Save(w http.ResponseWriter, r *http.Request) {
	name := strings.TrimSpace(r.FormValue("Name"))
	ispublic := strings.TrimSpace(r.FormValue("Public"))
	ifPublic := false
	if ispublic == "on" {
		ifPublic = true
	}
	if name == "" {
		_, _ = helper.WriteJSON(w, server.Fail("Name is not allowed to be empty."))
		return
	}
	if strings.HasPrefix(name, "_") {
		_, _ = helper.WriteJSON(w, server.Fail("Name is not allowed to start with _."))
		return
	}
	data := strings.TrimSpace(r.FormValue("Data"))

	proj := &CgsProj{
		Name:   name,
		Public: &ifPublic,
		Data:   data,
	}
	if r.FormValue("ID") != "" {
		id, err := primitive.ObjectIDFromHex(strings.TrimSpace(r.FormValue("ID")))
		if err == nil {
			proj.ID = id
		}
	}

	dataUserModel := base.GenerateDataUserModel(proj, r)
	cgsService := NewCgsService()
	err := cgsService.Save(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	_, _ = helper.WriteJSON(w, server.OK("Saved successfully!").WithData(bson.M{
		"id": proj.ID,
	}))

}

func ChangeName(w http.ResponseWriter, r *http.Request) {
	id, err := primitive.ObjectIDFromHex(strings.TrimSpace(r.FormValue("ID")))
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	name := strings.TrimSpace(r.FormValue("Name"))
	if name == "" {
		_, _ = helper.WriteJSON(w, server.Fail("Name is not allowed to be empty."))
		return
	}
	if strings.HasPrefix(name, "_") {
		_, _ = helper.WriteJSON(w, server.Fail("Name is not allowed to start with _."))
		return
	}
	ispublic := strings.TrimSpace(r.FormValue("Public"))
	ifPublic := false
	if ispublic == "on" {
		ifPublic = true
	}

	proj := &CgsProj{
		ID:     id,
		Name:   name,
		Public: &ifPublic,
	}
	dataUserModel := base.GenerateDataUserModel(proj, r)
	cgsService := NewCgsService()
	err = cgsService.ChangeName(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Saved successfully!"))
}

func ChangeData(w http.ResponseWriter, r *http.Request) {
	id, err := primitive.ObjectIDFromHex(strings.TrimSpace(r.FormValue("ID")))
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail("ID is empty"))
		return
	}
	publishId := strings.TrimSpace(r.FormValue("PublishId"))
	data := strings.TrimSpace(r.FormValue("Data"))

	proj := &CgsProj{
		ID:     id,
		Data: data,
		PublishId: publishId,
	}
	dataUserModel := base.GenerateDataUserModel(proj, r)
	cgsService := NewCgsService()
	err = cgsService.Update(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Update successfully!"))
}

func Delete(w http.ResponseWriter, r *http.Request) {
	id, err := primitive.ObjectIDFromHex(r.FormValue("ID"))
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail("ID is not allowed."))
		return
	}
	proj := &CgsProj{
		ID:     id,
	}
	dataUserModel := base.GenerateDataUserModel(proj, r)
	cgsService := NewCgsService()
	err = cgsService.Remove(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Delete successfully!"))
}

func List(w http.ResponseWriter, r *http.Request) {
	projType := r.FormValue("type")
	dataUserModel := base.GenerateDataUserModel(&CgsProj{
		Type: projType,
	}, r)
	cgsService := NewCgsService()
	results, err := cgsService.List(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.Result{
		Code: 200,
		Msg:  "Get Successfully!",
		Data: results,
	})
}

func ListJs(w http.ResponseWriter, r *http.Request) {
	fileType := r.FormValue("fileType")
	parentId := r.FormValue("parentId")
	dataUserModel := base.GenerateDataUserModel(&CgsProj{
		FileType: fileType,
		ParentId: parentId,
	}, r)
	cgsService := NewCgsService()
	results, err := cgsService.ListJs(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.Result{
		Code: 200,
		Msg:  "Get Successfully!",
		Data: results,
	})
}

func Get(w http.ResponseWriter, r *http.Request) {
	id, err := primitive.ObjectIDFromHex(strings.TrimSpace(r.FormValue("ID")))
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail("ID is not allowed to be empty."))
		return
	}
	proj := &CgsProj{
		ID:     id,
	}
	dataUserModel := base.GenerateDataUserModel(proj, r)
	cgsService := NewCgsService()

	result, err := cgsService.GetOne(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	modelRes := result.(*CgsProj)
	if modelRes.Type == "" {
		modelRes.Type = "ThreeD"
	}

	visual, err := cgsService.GetVisualByPublishId(modelRes.PublishId, modelRes.Type)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	if *visual.Status == 0 {  // 未发布
		// 检查权限
		if dataUserModel.User == nil {
			_, _ = helper.WriteJSON(w, server.Result{
				Code:    301,
				Msg:     "Have no permission!",
				Data:    bson.M{},
			})
		}

		if dataUserModel.User.HasVisualAuth(visual.ID.Hex()) {
			//_, _ = helper.WriteJSON(w, server.OK("Get successfully!").WithData(result))
			helper.WriteJSON(w, server.Result{
				Code: 200,
				Msg:  "Get Successfully!",
				Data: result,
			})

		} else {
			_, _ = helper.WriteJSON(w, server.Result{
				Code:    301,
				Msg:     "Have no permission!",
				Data:    bson.M{},
			})
		}

		return
	}

	_, _ = helper.WriteJSON(w, server.Result{
		Code: 200,
		Msg:  "Get Successfully!",
		Data: result,
	})
}
